package boot.spring.demo;

import com.hankcs.hanlp.restful.HanLPClient;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo2 {

    private static String LETTER_DIGIT_REGEX = ".*[a-z0-9A-z].*";
    private static String CHINSE_NUM = ".*[一二三四五六七八九十].*";

    private static String TO_REMOVE_TEXT = "相关栏目";

    public static void main(String[] args) {
        String filePath = "G:\\test\\source\\01.docx";
        String destPath = "G:\\test\\dest\\01.docx";
        String formart = "docx";
        Map<String, String> textMap = new HashMap<>();
        textMap.put("产品营销", "净水器产品");
        textMap.put("乌市", "广州市");
        wordTextSubstitution(filePath, destPath, formart, textMap);
    }

    private static boolean shouldTransfer(String sourceText) {
        return !(sourceText.matches(LETTER_DIGIT_REGEX) || sourceText.matches(CHINSE_NUM));
    }

    /**
     * @param filePath 替换文件所在路径
     * @param formart  替换文件扩展名
     * @param map      替换数据集合
     * @description: 替换word中的文字
     * @author: Mr.Jkx
     * @time: 2023/1/10 13:19
     */
    public static void wordTextSubstitution(String filePath,String destPath, String formart, Map<String, String> map) {
        String textPath = "";
        File file = new File(filePath);
        String fileName = file.getName();
        HanLPClient client = new HanLPClient("https://www.hanlp.com/api", "MTQ2N0BiYnMuaGFubHAuY29tOldJdk9iWFduSmRQaGYyaks=");
        try {
            if ("docx".equalsIgnoreCase(formart)) {
                if (fileName != null && fileName != "") {
                    String name = fileName.substring(0, fileName.length() - 5);
                    textPath = filePath.replaceAll(fileName, name + "_" + System.currentTimeMillis() + ".docx");
                }
                XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(filePath));
                // 替换段落中的指定文字
                Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();

                while (itPara.hasNext()) {
                    XWPFParagraph paragraph = itPara.next();
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (int i = 0; i < runs.size(); i++) {
                        String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition());
                        if (oneparaString != null) {
                            if (oneparaString.contains(TO_REMOVE_TEXT)) {
                                System.out.println("含有待删除文本，整段删除");
                                continue;
                            }
                            try {
                                System.out.println("替换前文本：" + oneparaString);
                                //每段最长150个字符，按符号分行处理。
                                if (oneparaString.length() <=150 && shouldTransfer(oneparaString)) {
                                    System.out.println("文本少于150字符，直接处理：" + oneparaString);
                                    oneparaString = client.textStyleTransfer(oneparaString, "gov_doc");
                                    //每分钟限制为50次
                                    Thread.sleep(1500L);
                                } else {
                                    //首先使用。进行分隔
                                    String[] subSentences = oneparaString.split(ChineseSymbolConsts.C_DOT);
                                    StringBuilder resultStr = new StringBuilder("");
                                    for(String t : subSentences) {
                                        //补充回去句号
                                        t = t + ChineseSymbolConsts.C_DOT;
                                        if (t.length() <=150 && shouldTransfer(t)) {
                                            System.out.println("第一次按句号分隔后已符合：" + t);
                                            String tResult = client.textStyleTransfer(t, "gov_doc");
                                            //每分钟限制为50次
                                            Thread.sleep(1500L);
                                            resultStr.append(tResult);
                                        } else {
                                            System.out.println("按句好分隔还是大于150,保留原句：" + t);
                                            resultStr.append(t);
                                        }
                                    }
                                    oneparaString = resultStr.toString();
                                }
                            } catch (Exception e) {
                                ;
                            }
                            runs.get(i).setText(oneparaString, 0);
                        }
                    }
                }

                // 创建新文件存放新内容
                FileOutputStream outStream = new FileOutputStream(destPath);
                document.write(outStream);
                outStream.close();
                System.out.println("--- SUCCESS！");
            } else if ("doc".equalsIgnoreCase(formart)) {
                if (fileName != null && fileName != "") {
                    String name = fileName.substring(0, fileName.length() - 4);
                    textPath = filePath.replaceAll(fileName, name + "_" + System.currentTimeMillis() + ".doc");
                }
                HWPFDocument document = new HWPFDocument(new FileInputStream(filePath));
                Range range = document.getRange();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    range.replaceText(entry.getKey(), entry.getValue());
                }
                // 创建新文件存放新内容
                FileOutputStream outStream = new FileOutputStream(destPath);
                document.write(outStream);
                outStream.close();
                System.out.println("--- SUCCESS！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

